<?php

namespace App\Http\Controllers\Home;

use Barryvdh\Debugbar\Middleware\Debugbar;
use Barryvdh\Debugbar\Twig\Extension\Debug;
use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Models\Shop\Cart;



class CartController extends Controller
{
    function index()
    {
        $carts = Cart::with('product')->where('customer_id', session('customer.id'))->get();
        //Debugbar::info($carts);
        //return session('customer.id');
        return view('home.cart')->with('carts',$carts)->with('count', Cart::count_cart($carts));
    }
    function store(Request $request)
    {
        return $request-all();
        //判断购物车是否有当前商品,如果有,那么 num +1
        $product_id = $request->product_id;
        $cart = Cart::where('product_id', $product_id)->where('customer_id', session('customer.id'))->first();


        if ($cart) {
            Cart::where('id', $cart->id)->increment('num');
            return;
        }

        //否则购物车表,创建新数据
        Cart::create([
            'product_id' => $request->product_id,
            'customer_id' => session('customer.id')
        ]);
    }
    function change_num(Request $request)
    {
        if ($request->type == 'add') {
            Cart::where('id', $request->id)->increment('num');
        } else {
            Cart::where('id', $request->id)->decrement('num');
        }
        return Cart::count_cart();
    }
}
